<template>
    <div class="main_container_gray" v-loading="showLoading">
        <div class="part" style="display: none;">
            <div class="title">打印方式</div>
            <div class="tags">
                <div class="tag item" v-for="(item, index) in printTypes" 
                    :key="'type_'+index" :class="{select: item.selected}"
                    @click="typeClick(item)" >{{ item.name }}</div>
            </div>
        </div>
        <div class="part mt15">
            <div class="title">打印显示字段</div>
            <el-tabs v-model="activeName" class="tabs" type="card" @tab-click="handleClick">
                <el-tab-pane v-for="(item, index) in tabs" :key="'tab_'+index" :label="item.label" :name="item.activeName">
                    <div class="tags" style="padding-left: 0;">
                        <div class="tag item" v-for="(_item, _index) in item.tags" 
                        :key="item.activeName+_index"  @click="tagClick(_item)" 
                        :class="{select: _item.selected, disable: !_item.isZhen&&(selectedSize=='4'||selectedSize=='5')}">
                        {{ _item.name }}</div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="part mt15" v-if="activeName!='customer' && activeName!='supplier'">
            <div class="title">打印尺寸</div>
            <div class="tags" style="padding-left: 15px;">
                <div class="tag item" v-for="(item, index) in sizes" 
                :key="'size_'+index" :class="{select: item.selected, disable: item.disabled}"
                @click="sizeClick(item)" >{{ item.name }}</div>
            </div>
        </div>
        <div class="part mt15" v-if="activeName!='receive' && activeName!='pay'">
            <div class="title">设置页眉</div>
            <div class="tags pageH">
                <el-input v-if="activeName=='sale'" v-model="saleCommitForm.pageHeader" clearable maxlength="20" placeholder="请输入页眉"></el-input>
                <el-input v-else-if="activeName=='purchase'" v-model="buyCommitForm.pageHeader" clearable maxlength="20" placeholder="请输入页眉"></el-input>
                <el-input v-else-if="activeName=='post'" v-model="postCommitForm.pageHeader" clearable maxlength="20" placeholder="请输入页眉"></el-input>
                <el-input v-else-if="activeName=='customer'" v-model="customerCommitForm.pageHeader" clearable maxlength="20" placeholder="请输入页眉"></el-input>
                <el-input v-else-if="activeName=='supplier'" v-model="supplierCommitForm.pageHeader" clearable maxlength="20" placeholder="请输入页眉"></el-input>
             </div>
        </div>
        <div class="part mt15" v-if="activeName!='receive' && activeName!='pay'">
            <div class="title">设置页脚</div>
            <div class="tags pageH">
                <el-input v-if="activeName=='sale'" v-model="saleCommitForm.pageBottom" clearable maxlength="20" placeholder="请输入页脚"></el-input>
                <el-input v-else-if="activeName=='purchase'" v-model="buyCommitForm.pageBottom" clearable maxlength="20" placeholder="请输入页脚"></el-input>
                <el-input v-else-if="activeName=='post'" v-model="postCommitForm.pageBottom" clearable maxlength="20" placeholder="请输入页脚"></el-input>
                <el-input v-else-if="activeName=='customer'" v-model="customerCommitForm.pageBottom" clearable maxlength="20" placeholder="请输入页脚"></el-input>
                <el-input v-else-if="activeName=='supplier'" v-model="supplierCommitForm.pageBottom" clearable maxlength="20" placeholder="请输入页脚"></el-input>
              </div>
        </div>
        <div class="bottom">
            <div class="btns">
                <el-button class="btn" :loading="btnLoading" @click="preview">{{btnLoading?'正在生成pdf...':'打印预览'}}</el-button>
                <el-button class="btn btn_primary_color" @click="saveSetting">保存</el-button>
            </div>
        </div>

        <!-- 条款 -->
         <el-dialog
            title="自定义条款内容"
            :visible.sync="showEditProvisionDialog"
            width="50%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 5, maxRows: 10}"
                    placeholder="请输入内容"
                    v-model="provisionTxt">
                </el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showEditProvisionDialog=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addProvision">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getOrderSet } from '@/api/order';
import { urlToPdf } from '@/api/common';
import { savePrintSetting, getPrintSettings } from '@/api/unicloudApi';

export default {
    name: 'setPrint',
    data() {
        return {
            showLoading: false,
            btnLoading: false,
            showEditProvisionDialog: false,  //条款设置
            corp: '',
            activeName: 'sale',
            selectedSize: '1',  //默认A4
            selectedType: '',
            provisionTxt: '',  //条款内容
            printTypes: [
                {name: '极速打印', value: '1', selected: false},
                {name: '快速打印', value: '2', selected: false},
            ],
            tabs: [], 
            sizes: [
                {name: 'A4', value: '1', selected: true, disabled: false},
                {name: 'A4二等分', value: '2', selected: false, disabled: false},
                {name: 'A4三等分', value: '3', selected: false, disabled: false},
                {name: '80mm', value: '4', selected: false, disabled: false},
                {name: '110mm', value: '5', selected: false, disabled: false},
            ],
            saleCommitForm: {
                pageHeader:  '销售单',
                pageBottom: ''
            },
            postCommitForm: {
                pageHeader:  '送货单',
                pageBottom: ''
            },
            buyCommitForm: {
                pageHeader:  '采购单',
                pageBottom: ''
            },
            customerCommitForm: {
                pageHeader:  '客户对账单',
                pageBottom: ''
            },
            supplierCommitForm: {
                pageHeader:  '供货商对账单',
                pageBottom: ''
            }
        }
    },
    created() {
        this.corp = this.$store.state.corpId
        this.initData()
    },
    methods: {
        async initData() {
            // 公共字段
            let commonFields = [
                {name: '打印条形码', field_name: 'barcode', selected: false, isZhen: false},
                {name: '打印产品编号', field_name: 'goods_no', selected: false, isZhen: false},
                {name: '打印条款', field_name: 'term', selected: false, isZhen: false},
                {name: '打印产品小计', field_name: 'total_product', selected: false, isZhen: true},
                {name: '打印产品图片', field_name: 'picture', selected: false, isZhen: false},
                {name: '打印规格', field_name: 'specifications', selected: false, isZhen: false},
                {name: '打印单位', field_name: 'unit', selected: false, isZhen: false},
                {name: '打印备注', field_name: 'remark', selected: false, isZhen: false},
                {name: '打印页码', field_name: 'page', selected: false, isZhen: false},
            ]
            this.tabs = [
                {label: '销售单', activeName:'sale', tags: [
                    {name: '打印客户电话', field_name: 'phone', selected: false, isZhen: false},
                    {name: '打印时间', field_name: 'sale_date', selected: false, isZhen: true},      
                    {name: '打印经办人', field_name: 'username', selected: false, isZhen: true},     
                    {name: '打印商品总价', field_name: 'goods_sum_price', selected: false, isZhen: true}, 
                    {name: '打印销售金额', field_name: 'order_price', selected: false, isZhen: true},
                    {name: '打印收款记录', field_name: 'payment_record', selected: false, isZhen: true},
                    {name: '打印店铺地址', field_name: 'corp_address', selected: false, isZhen: false},
                    {name: '打印店铺电话', field_name: 'corp_phone', selected: false, isZhen: false},
                ]},
                {label: '采购单', activeName:'purchase', tags: [
                    {name: '打印时间', field_name: 'purchase_date', selected: false, isZhen: true},
                    {name: '打印结款优惠', field_name: 'payment_discount', selected: false, isZhen: true},
                    {name: '打印商品总价', field_name: 'standard_price', selected: false, isZhen: true},
                    {name: '打印采购金额', field_name: 'sold_price', selected: false, isZhen: true},
                    {name: '打印付款记录', field_name: 'payment_record', selected: false, isZhen: true},
                    {name: '打印经办人', field_name: 'username', selected: false, isZhen: true},
                    {name: '打印供货商电话', field_name: 'phone', selected: false, isZhen: false}
                ]},
                {label: '送货单', activeName:'post', tags: [
                    {name: '打印客户电话', field_name: 'phone', selected: false, isZhen: false},
                    {name: '打印时间', field_name: 'sale_date', selected: false, isZhen: true},      
                    {name: '打印经办人', field_name: 'username', selected: false, isZhen: true},   
                    {name: '打印单价', field_name: 'unit_price', selected: false, isZhen: false},  
                    {name: '打印商品总价', field_name: 'goods_sum_price', selected: false, isZhen: true}, 
                    {name: '打印销售金额', field_name: 'order_price', selected: false, isZhen: true},
                    {name: '打印大写合计', field_name: 'big_total', selected: false, isZhen: true},
                    {name: '打印收款记录', field_name: 'payment_record', selected: false, isZhen: true},
                    {name: '打印店铺地址', field_name: 'corp_address', selected: false, isZhen: false},
                    {name: '打印店铺电话', field_name: 'corp_phone', selected: false, isZhen: false},
                ]},
            ]
            // 获取销售单设置
            await this.getOrderFiledSet()
            this.tabs.forEach(item => {
                // if (item.activeName=='sale' || item.activeName=='purchase'){
                item.tags = item.tags.concat(commonFields)
                // }
            })
            // 获取配置
            this.getPrintSetting()
        },
        // 获取自定义字段
        getOrderFiledSet() {
            let keyForName = [
                {key: 'delivery_address', name: '联系地址', isZhen: false},
                {key: 'rebates', name: '返点/红包', isZhen: false},
                {key: 'payment_discount', name: '结款优惠', isZhen: true},
            ]
            getOrderSet({corp: this.corp}).then(res => {
                let list = res.data.data.set_order_list
                if (list.length){
                    let setForm = list[0]
                    let arr = []
                    keyForName.forEach(item => {
                        if (setForm[item.key]) {
                            arr.push( {name: item.name, field_name: item.key, selected: false, isZhen: item.isZhen} )
                        }
                        // if (setForm.builder){
                        //     arr.push( {name: '施工人员', field_name: 'builds', selected: false, isZhen: false} )
                        // }
                        // if (setForm.builder){
                        //     arr.push( {name: '销售人员', field_name: 'sale', selected: false, isZhen: false} )
                        // }
                    })
                    this.tabs.forEach(item => {
                        if (item.activeName=='sale' || item.activeName=='post'){
                            item.tags = item.tags.concat(arr)
                        }
                    })

                    // 处理自定义字段
                    let set_field_name = setForm.set_field_name
                    if (!set_field_name){
                        return
                    }
                    for (var i = 1; i < 11; i++) {
                        let keyName = set_field_name['name'+i]
                        if (keyName) {
                            keyForName.push({
                                key: 'custom_field'+i,
                                name: keyName
                            })
                        }
                    }
                }
            })
        },
        // 获取打印配置
        getPrintSetting() {
            let that = this
            that.showLoading = true
            getPrintSettings({
                corp_id: this.corp,
                type: this.activeName
            }).then(res => {
                if (res.data.length) {
                    that.selectedSize = res.data[0].pageSize
                    that.selectedType = res.data[0].printType
                    that.provisionTxt = res.data[0].provision || ''
                    that.sizes.forEach(item => {
                        item.selected = false
                        if (item.value == that.selectedSize){
                            item.selected = true
                        }
                    })
                    that.printTypes.forEach(item => {
                        item.selected = false
                        if (item.value == that.selectedType){
                            item.selected = true
                        }
                    })
                    that.handleSettings(res.data[0])
                }else{
                    that.tabs.forEach(item => {
                        if (item.activeName == that.activeName){
                            item.tags.forEach(_item => {
                                _item.selected = false
                            })
                        }
                    })
                    that.sizes.forEach((item, index) => {
                        item.selected = false
                        if (index == 0){
                            item.selected = true
                        }
                    })
                }
                that.showLoading = false;
            })
        },
        // 处理数据
        handleSettings(data) {
            let that = this
            switch (this.activeName) {
                case 'sale':
                    if (data.fields.length){
                        that.tabs[0].tags.forEach(bItem => {
                            const aItem = data.fields.find(aItem => aItem.field_name === bItem.field_name);
                            if (aItem) {
                                bItem.selected = aItem.selected; // 更新 select 字段
                            }else{
                                bItem.selected = false
                            }
                        });
                    }else{
                        that.tabs[0].tags.forEach(item => {
                            item.selected = false
                        })
                    }
                    that.saleCommitForm.pageHeader = data.pageHeader
                    that.saleCommitForm.pageBottom = data.pageBottom
                    break;
                case 'purchase':
                    if (data.fields.length){
                        that.tabs[1].tags.forEach(bItem => {
                            const aItem = data.fields.find(aItem => aItem.field_name === bItem.field_name);
                            if (aItem) {
                                bItem.selected = aItem.selected; // 更新 select 字段
                            }else{
                                bItem.selected = false
                            }
                        });
                    }else{
                        that.tabs[1].tags.forEach(item => {
                            item.selected = false
                        })
                    }
                    that.buyCommitForm.pageHeader = data.pageHeader
                    that.buyCommitForm.pageBottom = data.pageBottom
                    break;
                case 'post':
                    if (data.fields.length){
                        that.tabs[2].tags.forEach(bItem => {
                            const aItem = data.fields.find(aItem => aItem.field_name === bItem.field_name);
                            if (aItem) {
                                bItem.selected = aItem.selected; // 更新 select 字段
                            }else{
                                bItem.selected = false
                            }
                        });
                    }else{
                        that.tabs[2].tags.forEach(item => {
                            item.selected = false
                        })
                    }
                    that.postCommitForm.pageHeader = data.pageHeader
                    that.postCommitForm.pageBottom = data.pageBottom
                    break;
                case 'customer':
                    that.customerCommitForm.pageHeader = data.pageHeader
                    that.customerCommitForm.pageBottom = data.pageBottom
                case 'supplier':
                    that.supplierCommitForm.pageHeader = data.pageHeader
                    that.supplierCommitForm.pageBottom = data.pageBottom
            
                default:
                    break;
            }
        },
        handleClick(val) {
            console.log(val.name, this.sizes[0].value)
            if (val.name=='receive' || val.name=='pay'){
                this.sizes[0].disabled = true
                this.sizes[0].selected = false
                this.sizes[1].selected = true
                this.selectedSize = this.sizes[1].value
                this.sizes[2].disabled = true
            }else{
                this.sizes[0].disabled = false
                this.sizes[0].selected = true
                this.sizes[1].selected = false
                this.selectedSize = this.sizes[0].value
                this.sizes[2].disabled = false
            }
            // 获取配置
            this.getPrintSetting()
        },
        typeClick(item) {
            this.printTypes.forEach(ele => {
                if (ele.value === item.value){
                    ele.selected = !ele.selected
                    this.selectedType = ele.selected ? ele.value : ''
                }else {
                    ele.selected = false
                }
            })
        },
        tagClick(item) {
            item.selected = !item.selected
            if (item.selected && item.name=='打印条款'){
                this.showEditProvisionDialog = true
            }
        },
        sizeClick(item) {
            if (item.disabled) return

            this.sizes.forEach(ele => {
                ele.selected = false
                if (ele.value === item.value){
                    ele.selected = true
                    this.selectedSize = ele.value
                }
            })
        },
        // 保存条款
        addProvision() {
            savePrintSetting({
                corp_id: this.corp,
                type: this.activeName,
                provision: this.provisionTxt
            }).then(res => {
                if (res.code == 200){
                    this.$message.success('保存成功')
                }
                this.showEditProvisionDialog = false
            })
        },
        // 自动保存
        saveSetting(type) {
            let params = {
                corp_id: this.corp,
                type: this.activeName,
                pageSize: this.selectedSize,
                printType: this.selectedType,
                fields: []
            }
            switch (this.activeName) {
                case 'sale':
                    params.pageHeader = this.saleCommitForm.pageHeader
                    params.pageBottom = this.saleCommitForm.pageBottom
                    params.fields = this.tabs[0].tags.filter(item => {return item.selected})
                    break;
                case 'purchase':
                    params.pageHeader = this.buyCommitForm.pageHeader
                    params.pageBottom = this.buyCommitForm.pageBottom
                    params.fields = this.tabs[1].tags.filter(item => {return item.selected})
                    break;
                case 'post':
                    params.pageHeader = this.postCommitForm.pageHeader
                    params.pageBottom = this.postCommitForm.pageBottom
                    params.fields = this.tabs[2].tags.filter(item => {return item.selected})
                    break;
                case 'customer':
                    params.pageHeader = this.customerCommitForm.pageHeader
                    params.pageBottom = this.customerCommitForm.pageBottom
                    break;
                case 'supplier':
                    params.pageHeader = this.supplierCommitForm.pageHeader
                    params.pageBottom = this.supplierCommitForm.pageBottom
                    break;
                default:
                    break;
            }
            if (this.selectedSize=='4' || this.selectedSize=='5'){
                params.fields = params.fields.filter(item => {
                    return item.isZhen
                })
            }
            
            if (type && type=='preview') {
                let jsonStr = JSON.stringify(params)
                params = {
                    corp_id: this.corp,
                    type: this.activeName,
                    draft_data: jsonStr
                }
            }
            savePrintSetting(params).then(res => {
                if (res.code == 200){
                    if (type && type=='preview') {
                        console.log('save ok')
                    }else{
                        this.$message.success('保存成功')
                    }
                }
            })
        },
        // 预览
        async preview() {
            this.btnLoading = true
            await this.saveSetting('preview')

            let pageType = '', pageUrl = '';
            switch (this.activeName) {
                case 'sale':
                    pageType = 'pdf_saleOrder'
                    pageUrl = 'https://anhuiyaoying.com/localPDF/saleOrder.html?corp='+this.corp+'&project=jcy'
                    break;
                case 'purchase':
                    pageType = 'pdf_purchaseOrder'
                    pageUrl = 'https://anhuiyaoying.com/localPDF/purchaseOrder.html?corp='+this.corp+'&project=jcy'
                    break;
                case 'post':
                    pageType = 'pdf_postOrder'
                    pageUrl = 'https://anhuiyaoying.com/localPDF/postOrder.html?corp='+this.corp+'&project=jcy'
                    break;
                case 'customer':
                    pageType = 'pdf_customerBill'
                    pageUrl = 'https://anhuiyaoying.com/pdf/customerBill.html?corp='+this.corp
                    break;
                case 'supplier':
                    pageType = 'pdf_supplierBill'
                    pageUrl = 'https://anhuiyaoying.com/pdf/supplierBill.html?corp='+this.corp
                    break;
                default:
                    break;
            }
            let print_dict = {}
            switch (this.selectedSize) {
                case '1':  //A4
                    print_dict = {}
                    break;
                case '2':  //A4二等分
                    print_dict = {
                        page_height: 19.8,
                        page_width: 21.0,
                        orientation: "portrait",
                        header_template: "",
                        footer_template: ""
                    }
                    break;
                case '3':  //A4三等分
                    print_dict = {
                        page_height: 9.3,
                        page_width: 21.0,
                        orientation: "portrait",
                        header_template: "",
                        footer_template: ""
                    }
                    break;
                case '4':  //80mm
                    print_dict = {
                        page_width: 8,
                        orientation: "portrait",
                        header_template: "",
                        footer_template: ""
                    }
                    break;
                case '5':  //110mm
                    print_dict = {
                        page_width: 11,
                        orientation: "portrait",
                        header_template: "",
                        footer_template: ""
                    }
                    break;
                default:
                    break;
            }
            this.btnLoading = false
            window.open(pageUrl)
            return
            urlToPdf({
                corpId: this.corp,
                pdf_file_add: {
                    unique_order_no: '',
                    unique_type: pageType,
                    show_filename: 'preview.pdf',
                    req_url: pageUrl
                },
                print_dict: print_dict
            }).then(res => {
                this.btnLoading = false
                if (res.code == 200){
                    window.open(res.data.pdf_url)
                }else{
                    this.$message.error(res.message)
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
	@import '../../style/mixin';
    .main_container_gray {
        min-height: 100%;
        background: #eee;
        padding: 0 0 56px 0;
        margin: 15px 18px;
        position: relative;
        .part {
            background: #fff;
            width: 100%;
            .title {
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
            }
            .tabs {
                padding: 0 15px;
            }
            .tags {
                display: flex;
                flex-wrap: wrap;
                padding: 5px 15px 15px 25px;
                align-items: center;
                .tag {
                    width: 100px;
                    height: 36px;
                    line-height: 36px;
                    text-align: center;
                    font-size: 14px;
                    border: 1px solid #ccc;
                    cursor: pointer;
                    border-radius: 2px;
                }
                .item {
                    width: 200px;
                    margin: 20px 30px 0 0;
                }
                .select {
                    color: #fff;
                    background: @blue;
                    border: none;
                }
                .disable {
                    display: none;
                    cursor: not-allowed;
                }
            }
            .pageH {
                width: 90%;
            }
        }
        .mt15 {
            margin-top: 15px;
        }
        .bottom {
            position: fixed;
            bottom: 0;
            left: 150px;
            right: 0;
            height: 50px;
            background: #fff;
            border: 1px solid #eee; /* 边框 */
            box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.5); /* 上边框阴影 */
            display: flex;
            align-items: center;
            justify-content: end;
            .btns {
                padding: 0 30px;
                display: flex;
                align-items: center;
                .btn {
                    margin-left: 20px;
                    height: 32px;
                    display: inline-flex;
                    align-items: center;
                }
            }
        }
    }
</style>